/** EventBus */
package client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/** Takes events and assigns a handler to handle the event 
 * depending on the class passed in * 
 * @author jessienewman
 * @version $Revision: 1.0 $
 */
public class EventBus {
	/**
	 * Field map.
	 */
	private final Map<Class<?>, List<Handler<?>>> map;
	
	/**
	 * Field bus.
	 */
	public static final EventBus BUS = new EventBus();

	/**
	 * Field LOGGER.
	 */
	private static final Logger LOGGER = Logger.getLogger(EventBus.class.getName());

	/** Takes events and assigns a handler to handle the event
	 *  depending on the class passed in */
	private EventBus() {
		map = new HashMap<Class<?>, List<Handler<?>>>();
	}

	/** 
	 * Assigns a handler to an event
	 * @param classy class containing information to pass
	 * @param handler handler to add to the map
	 * @param <T> generic
	 */
	public <T> void addHandler(Class<T> classy, Handler<? super T> handler) {
		List<Handler<?>> handlerList = map.get(classy); // $codepro.audit.disable com.instantiations.eclipse.analysis.audit.security.incompatibleTypesStoredInACollection
		if (handlerList == null) {
			handlerList = new ArrayList<Handler<?>>();
			map.put(classy, handlerList);
		} 
		handlerList.add(handler);
	}
	
	/** 
	 * Fires an event and calls handle on any handlers for the event
	 * @param event event to be handled
	 */
	public void fireEvent(Object event) {
		for (Handler h : map.get(event.getClass())) { // $codepro.audit.disable com.instantiations.eclipse.analysis.audit.security.incompatibleTypesStoredInACollection
			LOGGER.info("Handling a " + event + " with a " + h);
			h.handle(event);
		}
	}
	
	/**
	 * returns the super's toString
	
	 * @return String super's toString */
	public String toString() {
		return super.toString();
	}

}
